//
//  StatisAnalysisView.swift
//  ptbuy
//
//  Created by MyMac on 2024/12/3.
//

import SwiftUI
import CoreData


//统计分析
struct StatisAnalysisView: View {
    
    @Binding var statisAnalysis:Bool
    @Environment(\.managedObjectContext) private var viewContext
    
    @State private var type:Int8 = 1

    
    var body: some View {
        NavigationView {
 
            VStack{
                Divider()
                // 获取数据并加载到 WebView
                let htmlContent = loadChartData()
                WebView(htmlContent: htmlContent).frame(height: 300)
               
                let data = fechData()
                if data.count>0{
                    let  productTotalNum = data.map(\.total_product).reduce(0,+)//总条数
                    let productTotalPrice = data.map(\.total_price).reduce(0,+)//总价
                    
                    VStack {
                        HStack{
                            Button(action:{
                                type = 1
                            }){
                                Text("客户").frame(width:80,height:8).foregroundColor(.black)
                            }.padding()
                                .foregroundColor(.black)
                                .background(Color("btn")).opacity(0.8)
                                .cornerRadius(8)
                            Button(action:{
                                type = 2
                            }){
                                Text("收购人").frame(width:80,height:8).foregroundColor(.black)
                            }.padding()
                                .foregroundColor(.black)
                                .background(Color("btn")).opacity(0.8)
                                .cornerRadius(8)
                            Button(action:{
                                type = 3
                            }){
                                Text("总件数").frame(width:80,height:8).foregroundColor(.black)
                            }.padding()
                                .foregroundColor(.black)
                                .background(Color("btn")).opacity(0.8)
                                .cornerRadius(8)
                        }
                        
                        
                        List {
                            if type == 1 || type == 2{
                                // 表头部分
                                Section(header: HStack {
                                    
                                    if type == 1 {
                                        Text("客户").frame(
                                            maxWidth: .infinity,
                                            alignment: .center
                                        )
                                            .fontWeight(.bold)
                                    }
                                    
                                    if type == 2 {
                                        Text("收购人").frame(
                                            maxWidth: .infinity,
                                            alignment: .center
                                        )
                                            .fontWeight(.bold)
                                    }
                                    
                                   
                                    Spacer()
                                    Text("件数").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                    Spacer()
                                    Text("总价(元)").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                    Spacer()
                                    Text("交易时间").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                }.padding(.horizontal)) {
                                    // 数据行部分
                                    ForEach(data) { item in
                                        HStack {
                                            if type == 1 {
                                                Text(item.name ?? "").font(.system(size: 13)).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                            }
                                            
                                            if type == 2 {
                                                Text(item.agent_name ?? "").font(.system(size: 13)).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                            }
                                           
                                            Spacer()
                                            Text("\(item.total_product)").font(.system(size: 13)).frame(
                                                maxWidth: .infinity,
                                                alignment: .center
                                            )
                                            Spacer()
                                            Text("\(item.total_price)").font(.system(size: 13)).frame(
                                                maxWidth: .infinity,
                                                alignment: .center
                                            )
                                            Spacer()
                                            Text(item.time ?? "").font(.system(size: 13)).minimumScaleFactor(0.3).frame(
                                                maxWidth: .infinity,
                                                alignment: .center
                                            )
                                        }
                                        .padding(.vertical, 5)
                                    }
                                }
                                // 合计部分
                                Section {
                                    HStack {
                                        Text("总计")
                                            .fontWeight(.bold)
                                        Spacer()
                                        Text("\(productTotalNum)件")
                                            .fontWeight(.bold)
                                        Spacer()
                                        Text("\(productTotalPrice)元")
                                            .fontWeight(.bold)
                                    }
                                    .padding(.vertical, 10)
                                }
                            }
                            
                            if type == 3 {
                                // 表头部分
                                Section(header: HStack {
                                
                                    Text("名称").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                    Spacer()
                                    Text("价格(元)").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                    Spacer()
                                    Text("客户名称").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                    Spacer()
                                    Text("收购人").frame(
                                        maxWidth: .infinity,
                                        alignment: .center
                                    )
                                        .fontWeight(.bold)
                                }.padding(.horizontal)) {
                                    // 数据行部分
                                    ForEach(data) { item in
                                        
                                        
                                        let products = fechProduct(clientId:item.id ?? "")
                                        ForEach(products){ product in
                                            HStack {
                                              
                                                
                                                Text(product.product_name ?? "").font(.system(size: 13)).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                          
                                               
                                                Spacer()
                                                Text("\(product.product_price)").font(.system(size: 13)).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                                Spacer()
                                                Text(item.name ?? "").font(.system(size: 13)).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                                Spacer()
                                                Text(item.agent_name ?? "").font(.system(size: 13)).minimumScaleFactor(0.3).frame(
                                                    maxWidth: .infinity,
                                                    alignment: .center
                                                )
                                            }
                                            .padding(.vertical, 5)
                                        }
                                        
                                        
                                    }
                                }
                                // 合计部分
                                Section {
                                    HStack {
                                        Text("总计")
                                            .fontWeight(.bold)
                                        Spacer()
                                        Text("\(productTotalNum)件")
                                            .fontWeight(.bold)
                                        Spacer()
                                        Text("\(productTotalPrice)元")
                                            .fontWeight(.bold)
                                    }
                                    .padding(.vertical, 10)
                                }
                            }
                            
                        }
                        .listStyle(GroupedListStyle()) // 修改列表样式
                        
                        
                    }
                }
                    
                    
                    Spacer()
                }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                    // 创建渐变背景
                    LinearGradient(
                        gradient: Gradient(
                            colors: [
                                Color("startColor").opacity(
                                    10
                                ),
                                // 上半部分颜色，增加不透明度
                                Color("endColor").opacity(0.1)
                            ]// 上半部分颜色，增加不透明度
                        ),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                    .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
                )
                .navigationBarTitle("统计分析", displayMode: .inline) // 设置导航栏标题
                    .navigationViewStyle(
                        StackNavigationViewStyle()
                    ) // 推荐在全屏时使用此样式
                    .background()
                    .toolbar {
                        // 修改标题字体大小
                        ToolbarItem(placement: .topBarLeading) {
//                            Text("返回").font(.system(size: 18))
//                                .clipShape(
//                                    Capsule()
//                                ) // 使用 Capsule 形状来实现圆角效果
//                                .onTapGesture {
//                                    statisAnalysis = false
//                                }
                            Button(action: {       // 自定义返回动作
                                statisAnalysis = false
                                }) {
                                    Image(systemName: "arrow.left.circle.fill") // 返回图标
                                }
                        }
                    }
            
        }
        
        
    }
    func loadChartData() ->String{
        let data = fechData()
        var html:String = ""
        if data.count>0{
            let  productTotalNum = data.map(\.total_product).reduce(0,+)//总条数
            let productTotalPrice = data.map(\.total_price).reduce(0,+)//总价
            
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.groupingSeparator = ","
            formatter.locale = Locale(identifier: "en_US")
            let total =  formatter.string(from: NSNumber(value: productTotalPrice)) ?? "\(productTotalPrice)"
            let jsonData = """
            [
                {
                "name": "客户",
                "value": \(data.count)
                },
                {
                "name": "总件数",
                "value": \(productTotalNum)
                },
                {
                "name": "收购人",
                "value": \(data.count)
                }
            ]
            """
            
            
            
            // 构建 HTML 内容并将数据传递给 ECharts
             html = """
                   <!DOCTYPE html>
                   <html lang="en">
                   <head>
                       <meta charset="UTF-8">
                       <meta name="viewport" content="width=device-width, initial-scale=1.0">
                       <title>ECharts</title>
                       <script src="https://cdn.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js"></script>
                   </head>
                   <body>
                       <div id="chart" style="width: 100%; height: 300px;margin-top:10px;"></div>
                       <script>
                           var myChart = echarts.init(document.getElementById('chart'));

                          var option = {
                              title: {
                                  text: '总价：\(total)元',
                                  x: 'center'
                              },
                              tooltip: {
                                  trigger: 'item',
                                  formatter: "{a} <br/>{b} : {c} "
                              },
                              legend: {
                                  orient: 'vertical',
                                  x: 'left',
                                  data: ['客户','总件数','收购人']
                              },
                              toolbox: {
                                  show: true,
                                  feature: {
                                      mark: { show: true },
                                      dataView: { show: false, readOnly: false },
                                      magicType: {
                                          show: true,
                                          type: ['pie', 'funnel'],
                                          option: {
                                              funnel: {
                                                  x: '25%',
                                                  width: '50%',
                                                  funnelAlign: 'left',
                                                  max: 1548
                                              }
                                          }
                                      },
                                      restore: { show: true },
                                      // saveAsImage : {show: true}
                                  }
                              },
                              calculable: true,
                              series: [
                                  {
                                      name: '值',
                                      type: 'pie',
                                      radius: '55%',
                                      center: ['50%', '60%'],
                                      label: {
                                          normal: {
                                              position: 'inner',
                                              show: true,
                                              formatter: '{b}:{c}'
                                          }
                                      },
                                      data: \(jsonData)
                                  }
                              ]
                          };
                          myChart.setOption(option);
                      
                       </script>
                   </body>
                   </html>
                   """
           
        }
        return html
    }
    
    func fechData() ->[Client]{
        let fetchRequest: NSFetchRequest<Client> = Client.fetchRequest()
        do {
               let results = try viewContext.fetch(fetchRequest)
               return results
           } catch {
               print("Fetch failed: \(error)")
               return []
           }
    }
    
    func fechProduct(clientId:String) -> [Product]{
        let fetchRequest:NSFetchRequest<Product> = Product.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "pid = %@",clientId)
        do{
            let products = try viewContext.fetch(fetchRequest)
            return products
        }catch{
            return []
        }
    }
}
